package com.common.platform.sys.modular.system.controller;

import com.common.platform.sys.modular.system.entity.Dept;
import com.common.platform.sys.modular.system.entity.Menu;
import com.common.platform.sys.modular.system.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/thread")
@RequiredArgsConstructor
@Slf4j
public class ThreadController {

    private final TaskExecutor taskExecutor;


    @RequestMapping("/test")
    public void Test(String url) {
        for (int i = 0; i < 100; i++) {
            taskExecutor.execute(() -> {
                //down url
                log.info("执行任务:"+Thread.currentThread().getName());
            });
        }
    }


    private final DeptService deptService;
    private final DictService dictService;
    private final MenuService menuService;

    @GetMapping("/test1")
    public void Test1() throws Exception{


        CompletableFuture<String> dictFuture = CompletableFuture
                .supplyAsync(dictService::countAll, taskExecutor);
        CompletableFuture<String> deptFuture = CompletableFuture
                .supplyAsync(deptService::countAll, taskExecutor);

        CompletableFuture<List<String>> resultFuture = dictFuture.thenCombineAsync(deptFuture, (dictResult, deptResult) -> {
            List<String> resultDtoList = new ArrayList<>();
            resultDtoList.add(dictResult);
            resultDtoList.add(deptResult);
            return resultDtoList;
        }, taskExecutor);

        CompletableFuture<String> menuFuture = CompletableFuture
                .supplyAsync(menuService::countAll, taskExecutor);

        //阻塞任务全部完成
        CompletableFuture.allOf(dictFuture, resultFuture).join();
        log.info("dict,dept任务完成");
        List<String> strings = resultFuture.get();
        log.info(strings.toString());
        //任务
        CompletableFuture<List<String>> future = resultFuture
                .thenCombineAsync(menuFuture, (resultDtoList, menuResult)-> {
                    resultDtoList.add(menuResult);
                    return resultDtoList;
                }, taskExecutor);

        List<String> join = future.join();
        log.info(join.toString());
        log.info("所有任务完成");
    }

}
